import { useState, useCallback, useEffect } from 'react';
import { voiceRecognitionService } from '../services/voiceRecognitionService';
import { fallbackVoiceRecognitionService } from '../services/fallbackVoiceRecognitionService';

export const useVoiceRecording = () => {
    const [isRecording, setIsRecording] = useState(false);
    const [isProcessing, setIsProcessing] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [result, setResult] = useState<string>('');
    // 会话级累积文本：从“开始录音”到“停止录音”的完整转写
    const [sessionBuffer, setSessionBuffer] = useState<string>('');
    const [useFallback, setUseFallback] = useState(false);

    // 开始录音
    const startRecording = useCallback(() => {
        if (isRecording) {
            console.warn('正在录音中，无法重复开始');
            return;
        }

        setError(null);
        // 新一轮录音开始前清空显示与会话缓冲
        setResult('');
        setSessionBuffer('');

        // 选择使用哪个服务
        const service = useFallback ? fallbackVoiceRecognitionService : voiceRecognitionService;
        const serviceName = useFallback ? '浏览器原生' : '讯飞API';

        console.log(`使用${serviceName}语音识别服务`);

        service.startRecording(
            (text) => {
                console.log(`${serviceName}识别到文字:`, text);
                // 将每次返回的片段累加为整段文本
                setSessionBuffer(prev => {
                    const next = prev ? prev + text : text;
                    setResult(next);
                    return next;
                });
                setIsProcessing(false);
            },
            (error) => {
                console.error(`${serviceName}语音识别错误:`, error);

                // 如果是讯飞API错误且还没使用备用方案，则切换到浏览器原生
                if (!useFallback && fallbackVoiceRecognitionService.isSupported()) {
                    console.log('讯飞API连接失败，自动切换到浏览器原生语音识别');
                    setUseFallback(true);
                    setError('讯飞API连接失败，已切换到浏览器原生语音识别');
                    // 自动重试
                    setTimeout(() => {
                        startRecording();
                    }, 1000);
                } else {
                    setError(error);
                    setIsRecording(false);
                    setIsProcessing(false);
                }
            },
            (status) => {
                console.log(`${serviceName}语音识别状态:`, status);
                if (status === 'recording') {
                    setIsRecording(true);
                    setIsProcessing(false);
                } else if (status === 'processing') {
                    setIsProcessing(true);
                } else if (status === 'idle') {
                    setIsRecording(false);
                    setIsProcessing(false);
                }
            }
        );
    }, [isRecording, useFallback]);

    // 停止录音
    const stopRecording = useCallback(() => {
        if (isRecording) {
            const service = useFallback ? fallbackVoiceRecognitionService : voiceRecognitionService;
            service.stopRecording();
            setIsRecording(false);
            setIsProcessing(true);
        }
    }, [isRecording, useFallback]);

    // 清除结果
    const clearResult = useCallback(() => {
        setResult('');
        setSessionBuffer('');
        setError(null);
    }, []);

    // 清除错误
    const clearError = useCallback(() => {
        setError(null);
    }, []);

    // 清理资源
    useEffect(() => {
        return () => {
            voiceRecognitionService.disconnect();
            fallbackVoiceRecognitionService.cleanup();
        };
    }, []);

    // 手动切换服务
    const switchToFallback = useCallback(() => {
        if (isRecording) {
            console.warn('录音中无法切换服务');
            return;
        }
        setUseFallback(true);
        setError(null);
        console.log('已切换到浏览器原生语音识别');
    }, [isRecording]);

    const switchToXunfei = useCallback(() => {
        if (isRecording) {
            console.warn('录音中无法切换服务');
            return;
        }
        setUseFallback(false);
        setError(null);
        console.log('已切换到讯飞API语音识别');
    }, [isRecording]);

    return {
        isRecording,
        isProcessing,
        error,
        result,
        useFallback,
        startRecording,
        stopRecording,
        clearResult,
        clearError,
        switchToFallback,
        switchToXunfei
    };
};